//
//  YTPickerOrderView.m
//  YiTuDriverClient
//
//  Created by 石少庸 on 2017/7/27.
//  Copyright © 2017年 Yitu. All rights reserved.
//

#import "YTPickerOrderView.h"
#import "YTCarAndBonusModel.h"
#import "YTPickerCarViewCell.h"
#import "YTPriceBonusViewCell.h"
#import "YTPickerOrderNoUseViewCell.h"
#import <DZNEmptyDataSet/UIScrollView+EmptyDataSet.h>

#import "YTPickerOrderViewModel.h"
#import "YTUserProfileServices.h"
#import "YTDriverCarServices.h"
#import "YTDriverCarModel.h"
#import "YTPriceBonusModel.h"

@interface YTPickerOrderView ()<UITableViewDelegate, UITableViewDataSource, DZNEmptyDataSetSource, DZNEmptyDataSetDelegate>

// 顶部标题和价格
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *titleHeight;
@property (weak, nonatomic) IBOutlet UIView *titleView;
@property (weak, nonatomic) IBOutlet UILabel *priceText;
// 车辆
@property (weak, nonatomic) IBOutlet UIView *carView;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *carTableHeight;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *carHeight;
@property (weak, nonatomic) IBOutlet UITableView *carTableView;
@property (weak, nonatomic) IBOutlet UILabel *carTitle;
@property (weak, nonatomic) IBOutlet UIButton *carButton;
// 加价券
@property (weak, nonatomic) IBOutlet UIView *bonusView;
@property (weak, nonatomic) IBOutlet UITableView *bonusTableView;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *bonusTableHeight;
@property (weak, nonatomic) IBOutlet UILabel *bonusTitle;
@property (weak, nonatomic) IBOutlet UIButton *bonusButton;

@property (strong, nonatomic) UIView *pickerView;
@property (copy, nonatomic) NSString *bonusKey;
@property (copy, nonatomic) NSString *car_id;
@property (strong, nonatomic) YTPickerOrderViewModel *viewModel;

@end

@implementation YTPickerOrderView

#pragma mark - 初始化

- (instancetype)initWithFrame:(CGRect)frame
                        price:(NSString *)price
                     carBonus:(YTCarAndBonusModel *)model {
    self = [super initWithFrame:frame];
    if (self) {
        [self userinterfaceLayoutWith:model pirce:price];
        [self initViewAndData];
    }
    return self;
}

/** 页面布局*/
- (void)userinterfaceLayoutWith:(YTCarAndBonusModel *)model
                          pirce:(NSString *)price {
    _pickerView = [[NSBundle mainBundle] loadNibNamed:@"YTPickerOrderView" owner:self options:nil].firstObject;
    _pickerView.frame = self.bounds;
    [self addSubview:_pickerView];
    
    // 如果是个人司导则全部显示，如果是车队，则只显示加价券
    if (isDriver) {
        _priceText.text = [NSString stringWithFormat:@"¥ %@.00", price];
        _carTitle.text = model.carTitle;
    }
    
    if (isDriverTeam) {
        _titleHeight.constant = 0;
        for (UIView *view in _titleView.subviews) {
            [view removeFromSuperview];
        }
        
        _carHeight.constant = 0;
        for (UIView *view in _carView.subviews) {
            [view removeFromSuperview];
        }
    }
    _bonusTitle.text = (model.couponTitle.length ? model.couponTitle : @"无可用加价券");
    if ([_bonusTitle.text isEqualToString:@"无可用加价券"]) {
        _bonusTitle.textColor = kGrayColor;
    }
    
    // 加价券key和car_id
    _bonusKey = (model.couponKey.length ? model.couponKey : @"0");
    _car_id = (model.carId.length ? model.carId : @"0");
}

- (void)initViewAndData {
    _viewModel = [[YTPickerOrderViewModel alloc] init];
    _carTableView.tableFooterView = [UIView new];
    _bonusTableView.tableFooterView = [UIView new];
    _bonusKey = @"0";
    [_carTableView registerNib:[UINib nibWithNibName:@"YTPickerCarViewCell" bundle:nil] forCellReuseIdentifier:@"YTPickerCarViewCell"];
    [_bonusTableView registerNib:[UINib nibWithNibName:@"YTPriceBonusViewCell" bundle:nil] forCellReuseIdentifier:@"YTPriceBonusViewCell"];
    [_bonusTableView registerNib:[UINib nibWithNibName:@"YTPickerOrderNoUseViewCell" bundle:nil] forCellReuseIdentifier:@"YTPickerOrderNoUseViewCell"];
    @weakify(self);
    [[_viewModel.loadCarList.executionSignals switchToLatest] subscribeNext:^(id x) {
        @strongify(self);
        [self.carTableView reloadData];
    }];
    
    [[_viewModel.loadBonusList.executionSignals switchToLatest] subscribeNext:^(id x) {
        @strongify(self);
        [self.bonusTableView reloadData];
    }];
}

#pragma mark - Action

- (IBAction)showCarListAction:(UITapGestureRecognizer *)sender {
    if (_bonusButton.selected) { // 判断另一个table是否是展开的
        [self closeTable:NO];
    }
    _carButton.selected = !_carButton.selected;
    [_viewModel.loadCarList execute:RACTuplePack(_maxPassenger, _maxLuggage)];
    [self showCarTable:YES selected:_carButton.selected];
}

- (IBAction)showBonusListAction:(UITapGestureRecognizer *)sender {
    if (_carButton.selected) {
        [self closeTable:YES];
    }
    _bonusButton.selected = !_bonusButton.selected;
    [_viewModel.loadBonusList execute:nil];
    [self showCarTable:NO selected:_bonusButton.selected];
}

- (IBAction)backgroundClickAction:(UITapGestureRecognizer *)sender {
//    if (_backgroundClick) {
//        _backgroundClick();
//    }
    if ([self.delegate respondsToSelector:@selector(backgroundClickForDismiss)]) {
        [self.delegate backgroundClickForDismiss];
    }
}

- (IBAction)makeSurePickOrderAction:(UIButton *)sender {
    if (_pickOrderClick) {
        _pickOrderClick(RACTuplePack(_car_id, _bonusKey));
    }
}

#pragma mark - TableView

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return [tableView isEqual:_carTableView] ? _viewModel.carArray.count : _viewModel.bonusArray.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    if ([tableView isEqual:_carTableView]) {
        return 94;
    } else {
        if (indexPath.row == 0) {
            return 50;
        }
        return 120;
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    if ([tableView isEqual:_carTableView]) {
        YTPickerCarViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"YTPickerCarViewCell" forIndexPath:indexPath];
        cell.model = _viewModel.carArray[indexPath.row];
        return cell;
    } else {
        if (indexPath.row == 0) {
            YTPickerOrderNoUseViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"YTPickerOrderNoUseViewCell" forIndexPath:indexPath];
            return cell;
        }
        YTPriceBonusViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"YTPriceBonusViewCell" forIndexPath:indexPath];
        cell.model = _viewModel.bonusArray[indexPath.row];
        return cell;
    }
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    if ([tableView isEqual:_carTableView]) { // 选择车辆
        [self closeTable:YES];
        _carTitle.textColor = [UIColor blackColor];
        _carTitle.text = _viewModel.carArray[indexPath.row].carTitle;
    } else {
        [self closeTable:NO];
        if (indexPath.row == 0) { // 不使用加价券
            _bonusTitle.textColor = kGrayColor;
            _bonusTitle.text = @"不使用加价券";
            return;
        }
        // 使用加价券
        _bonusTitle.textColor = [UIColor blackColor];
        YTPriceBonusModel *model = _viewModel.bonusArray[indexPath.row];
        _bonusKey = model.key;
        _bonusTitle.text = [NSString stringWithFormat:@"%@-%@元", model.name, model.amount];
    }
}

#pragma mark - DZNEmptyDataSetSource

- (NSAttributedString *)titleForEmptyDataSet:(UIScrollView *)scrollView {
    NSString *text = ([scrollView isEqual:_carTableView] ? @"暂无可接此单车辆" : @"暂无可用加价券");
    NSDictionary *attributes = @{NSFontAttributeName: [UIFont boldSystemFontOfSize:17.0f],
                                 NSForegroundColorAttributeName: kGrayColor};
    return [[NSAttributedString alloc] initWithString:text attributes:attributes];
}

- (UIImage *)imageForEmptyDataSet:(UIScrollView *)scrollView {
    NSString *image = ([scrollView isEqual:_carTableView] ? @"empty_car" : @"empy_bonus");
    return [UIImage imageNamed:image];
}

#pragma mark - 展开和收起table
/**
 收起列表
 @param isCar 是否是车辆列表
 */
- (void)closeTable:(BOOL)isCar {
    if (isCar) {
        _carButton.selected = NO;
        [self showCarTable:YES selected:NO];
    } else {
        _bonusButton.selected = NO;
        [self showCarTable:NO selected:NO];
    }
}

/**
 展开列表

 @param isCar 是否是车辆列表
 @param selected 尖头的状态
 */
- (void)showCarTable:(BOOL)isCar selected:(BOOL)selected {
    [self updateConstraintsIfNeeded];
    if (isCar) {
        _carTableHeight.constant = (selected ? 153*2 : 0);
    } else {
        _bonusTableHeight.constant = (selected ? 120*2: 0);
    }
    [UIView animateWithDuration:0.3 animations:^{
        [self layoutIfNeeded];
    }];
}

@end
